use std::fmt::Display;

use axum::{
    body::Body,
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        Query,
    },
    http::Response,
    http::StatusCode,
    response::IntoResponse,
    routing::get,
    Router,
};
use crate::axum_return::{return_json_res,ResData};

pub struct MyResult<T>{
    pub err:Option<String>,
    pub data:Option<T>,
}

impl<T> MyResult<T>{
    pub fn err(err:String)->Self{
        MyResult{err:Some(err),data:None}
    }
    pub fn ok(t:T)->Self{
        MyResult{err:None,data:Some(t)}
    }
    pub fn into_rust(&self)->Result<&Option<T>,String>{
        if let Some(err)=&self.err{
            Err(err.clone())
        }else{
            Ok(&self.data)
    }
}
}

#[derive(Debug)]
pub struct Error{
    pub err:Option<String>,
}

impl From<std::io::Error> for Error {
    fn from(error: std::io::Error) -> Self {
        println!("{:?}",error);
        Error::new(error.to_string())
    }
}

impl Error{
    pub fn err<T:Into<String>>(t:T)->Self{
        Error{err:Some(t.into())}
    }
    pub fn new<T:Into<String>>(t:T)->Self{
        Self::err(t)
    }
    pub fn none()->Self{
        Error{err:None}
    }
    pub fn is_err(&self) -> bool {
        self.err.is_some()
    }
    pub fn to_string(&self)->String{
        self.err.clone().unwrap_or("".to_string())
    }
}

impl IntoResponse for Error {
    fn into_response(self) -> Response<Body> {
        if self.is_err(){
            return return_json_res(StatusCode::INTERNAL_SERVER_ERROR,ResData::new_msg(self.err.unwrap()),true);
        }
        return_json_res(StatusCode::INTERNAL_SERVER_ERROR,ResData::new_msg("服务器未知错误".to_string()),true)
    }
}